package com.atguigu.ting.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.app.BaseApp;
import com.atguigu.ting.realtime.bean.PayRechargeBean;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.util.AtguiguUtil;
import com.atguigu.ting.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/14 12:49
 */
public class DwsPayRechargeWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsPayRechargeWindow().init(
            40012,
            2,
            "DwsPayRechargeWindow",
            Constant.TOPIC_DWD_TRADE_RECHARGE
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 金额区间间隔
        final int rangeInterval = 100;
        // 金额区间 每个区间是前闭后开  比如: 100 属于 100-200这个区间
        final String[] amountRanges = new String[]{
            "0-100",
            "100-200",
            "200-300",
            "300-400",
            "400-500",
            "500+"
        };
        stream
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                double rechargeAmount = obj.getDouble("recharge_amount");
                // 计算支付金额所在的区间
                int index = (int) rechargeAmount / rangeInterval;
                String rechargeAmountRange = amountRanges[index < amountRanges.length ? index : (amountRanges.length - 1)];
                obj.put("recharge_amount_range", rechargeAmountRange);  // 增加支付区间字段
                return obj;
            })
            // 一个用户在一个金额区间一天多次支付算一个支付人数
            .keyBy(obj -> obj.getString("user_id") + "_" + obj.getString("recharge_amount_range"))
            .process(new KeyedProcessFunction<String, JSONObject, PayRechargeBean>() {
            
                private ValueState<String> lastRechargeDateState;
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastRechargeDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastRechargeDate", String.class));
                }
            
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<PayRechargeBean> out) throws Exception {
                    Long ts = obj.getLong("recharge_time");
                    String today = AtguiguUtil.tsToDate(ts);
                    String lastRechargeDate = lastRechargeDateState.value();
                    long rechargeUserCt = 0; // 充值人数
                    if (!today.equals(lastRechargeDate)) {
                        lastRechargeDateState.update(today);
                        rechargeUserCt = 1;
                    }
                    long rechargeCt = 1; // 充值次数
                
                    out.collect(PayRechargeBean.builder()
                                    .rechargeAmountRange(ctx.getCurrentKey().split("_")[1])
                                    .rechargeUserCt(rechargeUserCt)
                                    .rechargeCt(rechargeCt)
                                    .ts(ts)
                                    .build());
                
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<PayRechargeBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(PayRechargeBean::getRechargeAmountRange)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<PayRechargeBean>() {
                    @Override
                    public PayRechargeBean reduce(PayRechargeBean value1,
                                                  PayRechargeBean value2) throws Exception {
                        value1.setRechargeUserCt(value1.getRechargeUserCt() + value2.getRechargeUserCt());
                        value1.setRechargeCt(value1.getRechargeCt() + value2.getRechargeCt());
                        return value1;
                    }
                },
                new ProcessWindowFunction<PayRechargeBean, PayRechargeBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<PayRechargeBean> elements,
                                        Collector<PayRechargeBean> out) throws Exception {
                        PayRechargeBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                    
                        bean.setTs(System.currentTimeMillis());
                    
                        out.collect(bean);
                    }
                }
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_pay_recharge_window", PayRechargeBean.class));
        
    }
    
}
